package cn.wolfcode.servlet;

import cn.wolfcode.domain.File;
import cn.wolfcode.mapper.FileMapper;
import cn.wolfcode.utils.MybatisUtil;
import org.apache.ibatis.session.SqlSession;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.IOException;
import java.util.UUID;
@WebServlet("/xiugaiServlet")
@MultipartConfig(maxFileSize = 800000, maxRequestSize = 1400000)
public class xiugaiServlet extends HttpServlet {
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        SqlSession session = MybatisUtil.openSession();
        FileMapper fileMapper=session.getMapper(FileMapper.class);
        //Part part = req.getPart("filepath");
        for (Part part:req.getParts()){
            if(part.getName().startsWith("filepath")){
                String filename = getFilename(part);
                String fileName = getFileName(filename);
                String filePath = getFilePath(fileName);
                String realpath = getRealpath(fileName);
                part.write(realpath);
                Long uid = Long.parseLong(req.getParameter("uid")) ;
                File f = new File(filename,filePath,uid);
                System.out.println(f);
                fileMapper.insert(f);
                session.commit();
            }
        }
        session.close();
        resp.sendRedirect("/chaxunServlet");
    }
    private  String getFilename(Part part){
        // String realFileName = part.getSubmittedFileName();
        String cd = part.getHeader("Content-Disposition");
        //截取不同类型的文件需要自行判断
        String filename = cd.substring(cd.lastIndexOf("=")+2, cd.length()-1);
        System.out.println(filename);
        //String realFileName= filename ;
        return filename;
    }
    private String getFileName(String filename){
        String ext = filename.substring(filename.lastIndexOf("."));
        String fileName = UUID.randomUUID().toString() + ext;
        System.out.println(fileName);
        return fileName;
    }
    private String getRealpath(String fileName){
        String realPath = getServletContext().getRealPath("/upload") + "/" + fileName;
        System.out.println(realPath);
        return realPath;
    }
    private String getFilePath(String fileName){
        String via = "/upload/" + fileName;
        System.out.println(via);
        return via;
    }
}
